<template>
  <div style="max-width:400px;margin:100px auto;">
    <el-card>
      <h2 style="text-align:center;">ERP系统登录</h2>
      <el-form @submit.prevent="onLogin">
        <el-form-item label="用户名">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-button type="primary" style="width:100%;" @click="onLogin">登录</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const form = ref({ username: '', password: '' })
const userStore = useUserStore()
const router = useRouter()

const onLogin = async () => {
  const res = await axios.post('http://localhost:8081/api/user/login', form.value)
  if (res.data.code === 200) {
    userStore.setUserInfo(res.data.data.user)
    userStore.setToken(res.data.data.token)
    // 获取权限
    const permRes = await axios.get(`http://localhost:8081/api/user/${res.data.data.user.id}/permissions`, {
      headers: { Authorization: `Bearer ${res.data.data.token}` }
    })
    if (permRes.data.code === 200) {
      userStore.setPermissions(permRes.data.data)
      router.push('/')
    }
  } else {
    ElMessage.error(res.data.msg)
  }
}
</script> 